package com.heima.search.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到header中的信息
//        String userId = request.getHeader("userId");
//        Optional<String> optional = Optional.ofNullable(userId);
//
//        if(optional.isPresent()) {
//            //把用户id存入threadloacl中
//            ApUser apUser = new ApUser();
//            apUser.setId(Integer.valueOf(userId));
//            AppThreadLocalUtil.setUser(apUser);
//        }
//        return true;


        // AI
        String userId = request.getHeader("userId");
        log.info("Intercepted userId: {}", userId); // 打印 userId

        if (StringUtils.hasText(userId)) {
            try {
                Integer.parseInt(userId); // 验证是否是合法数字
                ApUser apUser = new ApUser();
                apUser.setId(Integer.valueOf(userId));
                AppThreadLocalUtil.setUser(apUser);
                log.info("Set user with ID: {}", userId);
            } catch (NumberFormatException e) {
                log.warn("Invalid userId format: {}", userId);
            }
        } else {
            log.warn("userId header is missing or empty.");
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtil.clear();
    }
}
